package com.joker.logquery.service;

import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;

/**
 * Description: logService
 *
 * @author Joker
 * @version 1.0.0
 */
@Service
public class LogService {
    private static final Logger logger = Logger.getLogger(LogService.class.getName());


    /**
     * 加载日志内容
     *
     * @param path
     * @param query
     * @return
     */
    public String getLogContent(String path, String query) {
        logger.info("Loading log content from file: " + path + ", query: " + query);
        // 判断路径合法性，支持 Linux 系统地址和 Windows 系统地址
        if (path == null || path.isEmpty()) {
            return "Invalid file path";
        }

        // 解码中文字符
        String decodedPath;
        try {
            decodedPath = URLDecoder.decode(path, StandardCharsets.UTF_8);
        } catch (Exception e) {
            logger.severe("Error decoding file path: " + e.getMessage());
            return "Error decoding file path: " + e.getMessage();
        }

        String filePath = decodedPath.replace("\\", "/");

        // 创建File对象，确保路径合法性
        File file = new File(filePath);
        if (!file.exists() || file.isDirectory()) {
            return "File does not exist or is a directory";
        }

        if (file.length() > 1024 * 1024) {
            String content = "File is too large <br> Only display the latest 1M content <br> ------------------------------------- <br> <br>";
            try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
                long length = raf.length();
                long start = length - 1024 * 1024;
                if (start < 0) {
                    start = 0;
                }
                raf.seek(start);
                byte[] bytes = new byte[(int) (length - start)];
                int read = raf.read(bytes);
                final String log = new String(bytes, 0, read, StandardCharsets.UTF_8);
                String[] lines = log.split("\n");
                StringBuilder logBuilder = new StringBuilder();
                for (int i = lines.length - 1; i >= 0; i--) {
                    String line = lines[i];
                    // 如果query不为空，且日志内容包含query，则高亮显示并且只返回改行
                    if (query != null && !query.isEmpty()) {
                        if (line.contains(query)) {
                            line = line.replace(query, "<span style=\"color:red\">" + query + "</span>");
                            logBuilder.append(line).append("<br>");
                        }
                    } else {
                        logBuilder.append(line).append("<br>");
                    }
                }
                logger.info("Log content loaded successfully");
                return content + logBuilder;
            } catch (IOException e) {
                logger.severe("Error reading log file: " + e.getMessage());
                return "Error reading log file: " + e.getMessage();
            }
        }

        // 懒加载文件内容
        List<String> contentLines = new LinkedList<>();
        try (BufferedReader br = new BufferedReader(new FileReader(file, StandardCharsets.UTF_8))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (query != null && !query.isEmpty()) {
                    if (line.contains(query)) {
                        line = line.replace(query, "<span style=\"color:red\">" + query + "</span>");
                        contentLines.add(line);
                    }
                } else {
                    contentLines.add(line);
                }
            }
        } catch (IOException e) {
            logger.severe("Error reading log file: " + e.getMessage());
            return "Error reading log file: " + e.getMessage();
        }

        if (contentLines.isEmpty()) {
            return "Log file is empty";
        }

        StringBuilder contentBuilder = new StringBuilder();
        for (int i = contentLines.size() - 1; i >= 0; i--) {
            String line = contentLines.get(i);
            contentBuilder.append(line).append("<br>"); // 添加换行标签
        }
        logger.info("Log content loaded successfully");
        return contentBuilder.toString();
    }
}
